package nayasis.common.model;

import java.lang.reflect.Field;

import nayasis.common.log.NLogger;
import nayasis.common.util.StringUtil;

/**
 * Common VO
 *
 * @author nayasis
 *
 */
public abstract class NVo {

	private final String LINE = "---------------------------------------------\n";

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString() {

		StringBuffer sb = new StringBuffer();

        Field[] fields = this.getClass().getDeclaredFields();

        sb.append( LINE );

        if( fields.length == 0 ) {
        	sb.append( "Nothing to print" );

        } else {

        	int maxLength = getMaxFieldNameLength( fields );

        	for( int inx = 0, inxCnt = fields.length; inx < inxCnt; inx++ ) {

        		Field field = fields[ inx ];

        		field.setAccessible( true );

        		printFieldName( sb, field, maxLength );

        		printFieldValue( sb, field );

        		sb.append( '\n' );

        	}
        }

        sb.append( LINE );

        return sb.toString();

	}

	private int getMaxFieldNameLength( Field[] fields ) {

		int result = 0;

		for( Field field : fields ) {
			result = Math.max( result, field.getName().length() );
		}

		return result;

	}

	private void printFieldName( StringBuffer sb, Field field, int columnLength ) {

        sb.append( StringUtil.rpad(field.getName(), ' ', columnLength) );
        sb.append( " : " );

	}

	private void printFieldValue( StringBuffer sb, Field field ) {

        try {
            sb.append( field == null ? "null" : field.get(this) );
        } catch ( Exception e ) {
            NLogger.sys.println( e );
        }

	}

}
